#include "StdAfx.h"
#include "RelationBuffer.h"
#include "StreamPage.h"


RelationBuffer::RelationBuffer()
{
	
	this->freePositionHead.pageIndex=0;
	this->freePositionHead.chunkIndex=0;

}


RelationBuffer::~RelationBuffer(void)
{
}
void RelationBuffer::insertElement(Element& element)
{
	assert(!isFull());
	MemoryPosition elementPosition = this->freePositionHead;

	this->setElementByMemoryPosition(element,elementPosition);
	this->idPositionMap.insert(make_pair(element.id,elementPosition));
	this->getNextPosition(elementPosition,freePositionHead);

}
void RelationBuffer::deleteElement(Element& element)
{
	DocumentId id = element.id;
	std::map<DocumentId, MemoryPosition>::iterator it;
	it = this->idPositionMap.find(id);
	assert(it!=this->idPositionMap.end());
	MemoryPosition elementPosition = it->second;
	this->setNextPosition(elementPosition,freePositionHead);
	this->freePositionHead = elementPosition;
	this->idPositionMap.erase(it);
}


bool RelationBuffer::isFull(void)
{
	bool ret;
	if(!isValidMemoryPosition(freePositionHead))
	{
		ret = this->allocateNewPage();
		if(ret == false)
		{
			return true;
		}
		this->freePositionHead.pageIndex = this->getPageNumber()-1;
		this->freePositionHead.chunkIndex = 0;

	}

	return false;
}